<template>
  <inject-template :item="item" :pageId="pageId" :popId="popId" :isPropagation="isPropagation">
    <template v-slot:common>
      <div v-if="isHtml2canvas" class="wb-scroll-container crop-con" :style="cropHeightStyle">
        <!-- <img :src="cropUrls && cropUrls[0]" class="crop-bg"> -->
        <div class="crop-bg" :style="cropBgStyle">
          <ul class="selected-lists crop-middle" :style="cropMiddleStyle" ref="cropDom">
            <li v-for="(item_, index) in selectedLists" :key="index" :style="getItemStyle(item_.position, item_)">
              <img :src="item_.resultUrl ? item_.resultUrl :item_.url">
            </li>
          </ul>
        </div>
        <img v-if="cropUrls && cropUrls[1]" :src="cropUrls[1]" class="crop-top" :style="getTopStyle">
        <img v-if="cropUrls && cropUrls[3]" :src="cropUrls[3]" class="crop-bottom" :style="getBottomStyle">
      </div>
      <div v-else class="wb-scroll-container">
        <template v-if="commonAttr.isVertical">
          <div v-if="commonAttr.isTouchMove"  class="swiper swiper-container vertical-scroll touch-move-wrapper" ref="scrollSwiper">
            <div class="swiper-wrapper" ref="wrapper">
              <div class="swiper-slide">
                <ul class="touch-move-con" :style="getTouchMoveStyle">
                  <li v-for="(item_, index) in lists" :key="index" :style="getTouchMoveItemStyle(item_.position)">
                    <wb-item-scroller :item="item" :qItem="item_" :index="index" :selecteds="selecteds"></wb-item-scroller>
                  </li>
                </ul>
                <p :style="styles" class="text">已经没有了哦</p>
              </div>
            </div>
            <!-- Add Scroll Bar -->
            <div class="swiper-scrollbar" ref="scrollBar"></div>
          </div>
          <div v-else-if="selectedLists.length > 0"  class="swiper swiper-container vertical-scroll" ref="scrollSwiper" >
            <div class="swiper-wrapper" ref="wrapper" :style="getSwiperStyle">
              <div class="swiper-slide">
                <ul class="selected-lists">
                  <li v-for="(item_, index) in selectedLists" :key="index" :style="getItemStyle(item_.position, item_)">
                    <img :src="item_.resultUrl ? item_.resultUrl :item_.url" class="slide-img">
                  </li>
                </ul>
              </div>
            </div>
            <!-- Add Scroll Bar -->
            <div class="swiper-scrollbar" ref="scrollBar"></div>
          </div>
          <div v-else ref="scrollSwiper"  class="swiper swiper-container vertical-scroll scroller-img-text-con">
            <div class="swiper-wrapper" ref="wrapper">
              <div class="swiper-slide">
                <img v-if="commonAttr.url" :src="commonAttr.url" class="slide-img" :style="conImgStyle">
                <div v-else-if="commonAttr.innerHtml" ref="innerHtml" v-html="innerHtml" :style="styles"></div>
              </div>
            </div>
            <!-- Add Scroll Bar -->
            <div class="swiper-scrollbar" ref="scrollBar"></div>
          </div>
        </template>
        <div v-else class="swiper swiper-container gallery-thumbs" ref="scrollSwiper" >
          <div class="swiper-wrapper" ref="wrapper">
            <div class="swiper-slide" v-for="(item,index) in lists" :style="getItemConStyle(item)" :key="item.id">
              <img v-show="item.url" :src="item.url" :style="itemStyle" ref="img" class="slide-img" @click="onAddDragItem($event.currentTarget, item,index)">
            </div>
          </div>
        </div>
      </div>
    </template>
  </inject-template>
</template>

<script>
import InjectTemplate from '@/components/inject-template.vue'
import WbItemScroller from '@/components/items/wb-item-scroller.vue'
import { utils } from '@/components/utils/utils'
import { commonUtils } from '@/components/utils/common-utils'
import { MOBILE_WID_HEI } from '@/common/const-dif'
import { EventBus } from '@/store/index'
import { COMPONENT_TYPES } from '@/common/const-wb'
import { SCROLLBER_TYPE_MAP } from '@/common/const'
import { bgPositionStyle } from '@/store/utils'
import { reactive } from 'vue'
import { getPxOVwByValue, getPxOrVw } from '@/store/utils'
import { getCompIdByParam } from '@/plugins/utils'

export default {
  name: 'WbScrollContainer',
  mixins: [utils, commonUtils],
  setup () {
    const state =  reactive({
      selecteds: [],
      selectedLists: [],
      isHtml2canvas: false,
      isTouchMove: false,
      cropUlHeight: 100,
    })
    const state_ = {
      topOffset: 0,
      count: 0,
      cropUrls: null,
      wrapper: null,
    }
    _.merge(state, state_)
    return state
  },
  created(){
    if(!window.Swiper){
      this.dynamicsLoadScript(this.env.baseUrl + 'js/swiper-bundle.min.js?v=7', 'Swiper', this.initSwiper)
      if(!this.isH5Edit){
        _.forEach(this.lists, (item) => {
          item.id = 'click_item_' + _.random(0, 1000);
        })
      }
    }
    //获取关联组件数据
    const relateAttrCompId = getCompIdByParam(this.commonAttr.relateAttrCompId);
    if(relateAttrCompId){
      const relateCompData = this.componentMap[relateAttrCompId];
      if(relateCompData.cid == COMPONENT_TYPES.wb_scroll_container || relateCompData.cid == COMPONENT_TYPES.wb_pixis){
        let lists = this.formValues[relateAttrCompId] && this.formValues[relateAttrCompId].lists;
        if(lists){
          _.forEach(this.formValues[relateAttrCompId].selecteds, (index) => {
            this.selectedLists.push(lists[index]);
          })
        }
      }
    }
    let cropUrlStr = this.commonAttr.cropUrls;
    if(cropUrlStr){
      this.cropUrls = cropUrlStr.split(',');
      if(this.cropUrls.length > 0) {
        this.isHtml2canvas = true;
        if(this.commonAttr.cropUrlsHeight)
        this.cropUrlsHeight = this.commonAttr.cropUrlsHeight.split(",");
      }
    }
    EventBus.$on("swiperChangePage", this.onUpdateSwiper);
    this.item.isCreated = true;
  },
  components: {
    InjectTemplate,
    WbItemScroller,
  },
  computed: {
    isPropagation(){
      return !this.commonAttr.isVertical && !this.isHtml2canvas
    },
    getSwiperStyle(){
      if(this.commonAttr.isVerticalCenter){
        return {
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          flexDirection: "column",
        }
      }
    },
    getTopStyle() {
      let cropUrlsHeights = this.cropUrlsHeight;
        //背景,框上部,框中部拉伸,框下部的Url偏移量
      return {
        height: getPxOVwByValue(cropUrlsHeights[1]),
      }
    },
    getBottomStyle() {
      let cropUrlsHeights = this.cropUrlsHeight;
      return {
        height: getPxOVwByValue(cropUrlsHeights[3]),
      }
    },
    innerHtml(){
      let html = this.commonAttr.innerHtml;
      html = html.replace(/《/g, "<");
      html = html.replace(/》/g, ">");
      return html;
    },
    conImgStyle(){
      let unit = getPxOrVw();
      return {
        margin: this.commonAttr.marginTB + unit + ' ' + this.commonAttr.marginLR + unit,
        padding: this.commonAttr.paddingTB + unit + ' ' + this.commonAttr.paddingLR + unit,
      }
    },
    conStyle(){
      let unit = getPxOrVw();
      return {
        width: getPxOVwByValue(this.commonAttr.itemBgWidth),
        height: getPxOVwByValue(this.commonAttr.itemBgHeight),
        margin: '0 ' + this.commonAttr.marginLR + unit
      }
    },
    itemStyle(){
      let unit = getPxOrVw();
      let isBackground = this.item.commonAttr.isBackground;
      if(isBackground){
        return {
          borderRadius: "10%",
          width: "inherit",
        }
      }else{
        return {
          objectFit: "contain",
          width: this.commonAttr.itemWidth + unit,
          height: this.commonAttr.itemHeight + unit,
          marginTop: this.commonAttr.paddingTB + unit,
        }
      }
    },
    getTouchMoveStyle(){
      let ys = [];
      let itemHeight = 0;
      let arr;
      _.forEach(this.lists, (item) => {
        arr = item.position.split(',');
        ys.push(parseInt(arr[1]));
        itemHeight = arr[3];
      })
      ys = ys.sort(function(a, b){return a - b});
      return {
        height: getPxOVwByValue(parseInt(ys[ys.length - 1]) + parseInt(itemHeight))
      }
    },
    cropBgStyle(){
      let bg = this.cropUrls[0];
      if(bg) {
        return {
          backgroundImage: 'url(' + bg + ')',
        }
      } else {
        return {}
      }
    },
    cropMiddleStyle(){
      let unit = getPxOrVw();
      let middleUrl = this.cropUrls[2];
      if(middleUrl) {
        let cropUrlsHeights = this.cropUrlsHeight;
        let cropUrlsOffsets = this.commonAttr.cropUrlsOffset && this.commonAttr.cropUrlsOffset.split(',');
        let topOffset = 0
        if(cropUrlsOffsets) {
          topOffset = parseFloat(cropUrlsOffsets[1])
        }
        return {
          backgroundImage: 'url(' + middleUrl + ')',
          top: getPxOVwByValue(Math.round(cropUrlsHeights[1]/MOBILE_WID_HEI.adaptiveScale)+topOffset),
          padding: this.commonAttr.paddingTB + unit + ' ' + this.commonAttr.paddingLR + unit
        }
      } else {
        return {}
      }
    },
    cropHeightStyle(){
      if(this.isH5Edit){
        return {}
      }else{
        this.computeCropUlHeight();
        let offsetHeight = parseInt(this.item.conAttr.height - this.cropUlHeight*MOBILE_WID_HEI.adaptiveScale);
        let groupCompId = this.item.commonAttr.groupCompId;
        let groupCompData = this.componentMap[groupCompId];
        // 更新截图打组容器属性高度和背景
        // groupCompData.conAttr.height = groupCompData.conAttr.height - offsetHeight;
        if(groupCompData){
          let conStyles = {
            height: getPxOVwByValue(groupCompData.conAttr.height - offsetHeight),
          }
          if(groupCompData.commonAttr.bgUrl) {
            _.merge(conStyles, {
              backgroundImage: 'url(' +  groupCompData.commonAttr.bgUrl + ')',
              backgroundSize: '100% 100%',
              backgroundRepeat: 'no-repeat',
            });
          }
          this.$store.commit("updateComponentAttr", { id: groupCompId, conStyles });
        }
        return {
          height: this.cropUlHeight + 'px'
        }
      }
    }
  },
  mounted(){
    this.wrapper = this.$refs.wrapper;
    this.initSwiper(window.Swiper);
  },
  methods: {
    getItemConStyle(item){
      let unit = getPxOrVw();
      let isBackground = this.item.commonAttr.isBackground;
      if(isBackground || !item.url){
        return {
          width: getPxOVwByValue(this.commonAttr.itemBgWidth),
          height: getPxOVwByValue(this.commonAttr.itemBgHeight),
          margin: '0 ' + this.commonAttr.marginLR + unit
        }
      }else{
        let styles_ = {
          backgroundImage: 'url(' + this.commonAttr.itemBgUrl + ')',
          width: getPxOVwByValue(this.commonAttr.itemBgWidth),
          height: getPxOVwByValue(this.commonAttr.itemBgHeight),
          margin: '0 ' + this.commonAttr.marginLR + unit,
          backgroundSize: 'contain',
        }
        bgPositionStyle(styles_, this.item.commonAttr.bgPositionRepeatType);
        return styles_;
      }
    },
    initSwiper(Swiper) {
      if(!Swiper || this.swiper || this.isHtml2canvas){
        return
      }
      if(this.commonAttr.isVertical){
        if(this.commonAttr.isTouchMove){
          this.swiper = new Swiper('.swiper-container', {
            direction: 'vertical',
            slidesPerView: 'auto',
            freeMode: true,
            scrollbar: {
              el: '.swiper-scrollbar',
            },
            mousewheel: true,
            on: {
              touchMove: () => {
                window.cancelAnimationFrame(this.scrollCb);
                this.isTouchMove = true;
              },
              touchEnd: () => {
                let arr = this.wrapper.style.transform.split(',');
                if(arr[1]){
                  this.topOffset = arr[1].split('px')[0];
                }
                if(this.isTouchMove){
                  this.loop();
                }
                this.isTouchMove = false;
              },
            }
          });
          this.scrollCb = window.requestAnimationFrame(this.loop);
        }else{
          if(this.commonAttr.url){
            let img = new Image();
            img.onload = () => {
              this.initScrollbar(Swiper);
            };
            img.src = this.commonAttr.url;
          }else{
            this.initScrollbar(Swiper);
          }
          document.documentElement.style.setProperty(`--swiper-scrollbar-drag-bgcolor`, SCROLLBER_TYPE_MAP[this.commonAttr.scrollbarType]);
        }
      }else{
        this.initHorizontalSwiper(Swiper);
        // this.resetList();
      }
      // if(this.swiper){
      //   this.swiper.update(true);
      // }
    },
    onUpdateSwiper() {
      if(this.swiper){
        this.swiper.destroy();
        this.swiper = null;
        this.initHorizontalSwiper(Swiper);
        // this.resetList();
        // this.swiper.update(true);
      }
    },
    initScrollbar(Swiper){
      this.swiper = new Swiper(this.$refs.scrollSwiper, {
        direction: 'vertical',
        slidesPerView: 'auto',
        freeMode: true,
        scrollbar: {
          el: this.$refs.scrollBar,
        },
        mousewheel: true,
      });
    },
    initHorizontalSwiper(Swiper){
      this.cb = window.setInterval(() => {
        let len = document.getElementsByClassName("swiper-slide").length;
        if(len == this.lists.length) {
          window.clearInterval(this.cb);
          const slidesPerView = this.commonAttr.slidesPerView ? this.commonAttr.slidesPerView : 4.5;
          const spaceBetween = (MOBILE_WID_HEI.width - slidesPerView*this.commonAttr.itemBgWidth)/slidesPerView;
          this.swiper = new Swiper('.gallery-thumbs', {
            spaceBetween: spaceBetween,
            slidesPerView: slidesPerView,
            loop: false,
            freeMode: true,
            watchSlidesVisibility: true,
            watchSlidesProgress: true,
          });
        }
      }, this.siteInfo.reloadTime);

    },
    loop(){
      this.topOffset -= this.commonAttr.speed || 1;
      this.wrapper.style.scrollTop = this.topOffset;
      if(-this.topOffset >= this.wrapper.scrollHeight - this.wrapper.clientHeight){
        window.cancelAnimationFrame(this.scrollCb);
      }else{
        this.wrapper.style.transform = 'translate3d(0px, ' + this.topOffset + 'px, 0px)';
        this.scrollCb = window.requestAnimationFrame(this.loop);
      }
    },
    //初始化的时候需要初始化拖动最长的长度
    resetList(){
      if(this.isH5Edit){
        return
      }
      window.setTimeout(() => {
        let lists = [];
        _.forEach(this.lists, (item) => {
          if(item.url){
            lists.push(item);
          }
        })
        this.$store.commit("replaceComponentAttr", { id: this.item.id, lists });
      }, 100)
    },
    onAddDragItem(target, item_,index){
      const item = { img: target, url: item_.url };
      let isBackground = this.item.commonAttr.isBackground;
      let wid = target.naturalWidth/MOBILE_WID_HEI.adaptiveScale;
      let hei = target.naturalHeight/MOBILE_WID_HEI.adaptiveScale;
      let ratio = _.max([wid/MOBILE_WID_HEI.clientWidth, hei/MOBILE_WID_HEI.clientHeight]);
      if(ratio > 0.5){
        wid = wid/2;
        hei = hei/2;
      }
      item.width = wid;
      item.height = hei;

      this.item.commonAttr.itemIndex = index
      if(isBackground){
        EventBus.$emit("addImgToCanvasBg", item);
      }else{
        EventBus.$emit("addImgToCanvas", item);
      }
    },
    getTouchMoveItemStyle(positionStr){
      let position = positionStr.split(',');
      return {
        left: getPxOVwByValue(position[0]),
        top: getPxOVwByValue(position[1]),
        width: getPxOVwByValue(position[2]),
        height: getPxOVwByValue(position[3]),
      }
    },
    getItemStyle(positionStr, item = {}){
      let style_ = {};
      if(this.commonAttr.isVerticalCenter) {
        style_ =  {
          margin: 0
        }
      } else {
        let position = positionStr.split(',');
        style_ = {
          width: getPxOVwByValue(position[2]),
          height: getPxOVwByValue(position[3]),
        }
      }
      return style_
    },
    computeCropUlHeight() {
      if(this.isHtml2canvas && this.$refs.cropDom){
        if(this.cropUrlsHeight) {
          let cropUrlsHeights = this.cropUrlsHeight;
          //背景,框上部,框中部拉伸,框下部的Url偏移量
          let cropUrlsOffsets = this.commonAttr.cropUrlsOffset.split(',');
          let bottomOffset = cropUrlsOffsets[3] ? parseFloat(cropUrlsOffsets[3]) : 0;
          this.cropUlHeight = this.$refs.cropDom.offsetHeight + Math.round((parseInt(cropUrlsHeights[1])+parseInt(cropUrlsHeights[3]))/MOBILE_WID_HEI.adaptiveScale)+bottomOffset;
        } else {
          this.cropUlHeight = this.$refs.cropDom.offsetHeight
        }
      }
    }
  },
  beforeUnmount(){
    window.cancelAnimationFrame(this.scrollCb);
    EventBus.$off("swiperChangePage", this.onUpdateSwiper);
    if(this.swiper) {
      this.swiper.destroy()
    }
  },
  updated(){
    if(this.isHtml2canvas){
      this.computeCropUlHeight();
    }
  }
};
</script>

<style lang="scss" scope>
:root{
  --swiper-scrollbar-drag-bgcolor: #cf8910;
}
.wb-scroll-container{
  width: inherit;
  height: inherit;
  position: relative;

  .swiper-container {
    width: 100%;
    height: 100%;
  }

  .touch-move-wrapper {
    .touch-move-con{
      li{
        position: absolute;

        .bubble{
          position: absolute;
          top: 0;
          left: 0;
        }

        img{
          width: 100%;
          object-fit: contain;
        }
      }
    }
    .text{
      text-align: center;
      color: #ffffff;
      font-size: var(--size-12);
    }
    .swiper-scrollbar {
      background-color: transparent;
    }
    .swiper-scrollbar-drag {
      background-color: transparent;
    }
  }

  .scroller-img-text-con{
    .swiper-scrollbar-drag {
      background-color: var(--swiper-scrollbar-drag-bgcolor);
      opacity: 0.8;
    }
  }

  .selected-lists{
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
    padding-bottom: var(--size-24);
    li{
      display: inline-block;
      margin-top: var(--size-12);
      margin-bottom: var(--size-12);
    }
    img{
      width: 100%;
      object-fit: contain;
    }
  }

  .vertical-scroll {
    .swiper-slide {
      height: auto;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
    }
    .slide-img{
      width: 100%;
      object-fit: contain;
    }
  }

  .gallery-thumbs{
    .swiper-slide{
      display: flex;
      justify-content: center;
      justify-items: center;
    }
  }
}
.crop-con{
  .crop-bg{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-size: 100% 100%;
  }
  .crop-top{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
  }
  .crop-middle{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    background-repeat: no-repeat;
    background-size: 100% 100%;

    img {
      width: 100%;
      object-fit: contain;
    }
  }
  .crop-bottom{
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
  }
}
</style>
